<template>
  <base-window :top="top" :unique="unique" :title="$t('task.tip.proposeApproveTip1')" size="small" :show.sync="visible" :options="options" width="432px" class="task-need-approve-dialog" @closed="close">
    <div class="base-modal-content">
      <p><span class="form-item-required" v-if="remarkRequired">*</span>{{$t('task.detail.components.approveDesc')}}：</p>
      <!-- <textarea v-model="apprForm.applyRemark" :placeholder="remarkPlaceholder" rows="3" maxlength="500" /> -->
      <biz-at-textarea class="biz-at-textarea" ref="atTextarea" search-url="/message/user/lists" name-key="displayName" v-model="apprForm.applyRemark" :at-users.sync="atUsers" direction="bottom">
        <template slot="item" slot-scope="item">
          <img :src="head(item.user.head)">
          <span>{{item.user.displayName}}</span>
        </template>
        <textarea ref="editor" class="base-at-textarea" @input="inputContent" :placeholder="remarkPlaceholder" maxlength="500" :rows="3"></textarea>
      </biz-at-textarea>

      <!-- 高级审批流程处理 -->
      <template v-if="fromVip">
        <div class="vip-info">{{$t('common.zhongqi.vipApproveTipText')}}:</div>
        <div class="approve-steps">
          <el-steps direction="vertical">
            <el-step v-for="(item, index) in vipList" :key="index" :title="setNameLanguage(item.data)" status="process">
              <el-row slot="description" type="flex">
                <div class="form-item-control">
                    <label>{{$t('common.base.approveUser')}}：</label>
                    <template v-if="(item.data && item.data.attribute && item.data.attribute.candidate)">
                        <span>
                          {{ item.data.attribute.candidate | vipApproveNames }}
                        </span>
                    </template>
                    <template v-else>
                      {{$t('task.tip.approveTip8', {name: $t('task.edit.approvers')})}}
                    </template>
                </div>
              </el-row>
            </el-step>
          </el-steps>
        </div>
      </template>
      <template v-else>
        <!--S 常规 审批步骤 -->
        <div class="approve-steps">
          <el-row v-if="approveLevel === 1" :type="chooseApprover ? '' : 'flex'">
            <p>{{$t('common.base.approveUser')}}：</p>
            <form-user
              v-if="chooseApprover"
              show-tag-if-sp-user
              :field="{ displayName: $t('common.base.approveUser') }"
              v-model="approver"
              :see-all-org="true"
              :placeholder="$t('task.tip.approveTip6')"
            />
            <template v-else>
              <template v-if="isOpenData && approversStaffIds.length">
                <open-data v-for="staffId in approversStaffIds" :key="staffId" type="userName" :openid="staffId"></open-data>
              </template>
              <template v-else>
                {{getApproversLabel(approversName)}}
              </template>
            </template>
          </el-row>
          <el-steps v-else direction="vertical">
            <!-- 一级审批步骤 -->
            <el-step :title="$t('common.base.approveLevel', {data1: $t('common.base.number1')})" status="process">
              <el-row slot="description" type="flex">
                <div class="form-item-control">
                  <form-user
                    v-if="chooseApprover"
                    show-tag-if-sp-user
                    :field="{ displayName: $t('common.base.approveLevelUser', {data1: $t('common.base.number1')})}"
                    v-model="approver"
                    :see-all-org="true"
                    :placeholder="$t('task.tip.approveTip7', {data: $t('common.base.number1')})"
                  />
                  <div v-else>
                    <label>{{$t('common.base.approveUser')}}：</label>
                    <template v-if="isOpenData && approversStaffIds && approversStaffIds.length">
                      <open-data v-for="staffId in approversStaffIds" :key="staffId" type="userName" :openid="staffId"></open-data>
                    </template>
                    <template v-else>
                      {{getApproversLabel(approversName)}}
                    </template>
                  </div>
                </div>
              </el-row>
            </el-step>
            <!-- 二级以上审批步骤 -->
            <el-step v-for="(item, idx) in multiApproverSetting" :key="idx" :title="$t('common.base.approveLevel', {data1: cnNumName[idx + 2]})" status="process">
              <el-row slot="description" type="flex">
                <div class="form-item-control">
                  <form-user
                    v-if="item.isOpt === 1"
                    show-tag-if-sp-user
                    :field="{ displayName: $t('common.base.approveLevelUser', {data1: cnNumName[idx + 2]})}"
                    :value="item.approver"
                    @input="(val) => updateApprover(val, idx)"
                    :see-all-org="true"
                    :placeholder="$t('task.tip.approveTip7', {data: cnNumName[idx + 2]})"
                  />
                  <div v-else>
                    <label>{{$t('common.base.approveUser')}}：</label>
                    <template v-if="isOpenData && (item.approversStaffIds || item.approversStaffId)">
                      
                      <template v-if="item.approversStaffIds">
                        <open-data v-for="staffId in item.approversStaffIds.split(',')" :key="staffId" type="userName" :openid="staffId"></open-data>
                      </template>
                      <template v-else-if="item.approversStaffId">
                        <open-data v-for="staffId in item.approversStaffId.split(',')" :key="staffId" type="userName" :openid="staffId"></open-data>
                      </template>
                      
                    </template>
                    <template v-else>
                      {{getApproversLabel(item.approversName)}}
                    </template>
                  </div>
                </div>
              </el-row>
            </el-step>
          </el-steps>
        </div>
      </template>
      <!--E 审批步骤 -->

    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="submit" :loading="pending">{{$t('common.base.submit')}}</el-button>
    </div>
  </base-window>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform'
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
import _ from 'lodash'
import FormUser from '@src/component/form/components/FormUser/FormUser.vue';
import { getOssUrl } from '@src/util/assets'
const defaultAvatar = getOssUrl('/avatar.png')
import {enCodeAtText, getReceivers} from '@src/util/atText'
import { cutAtTextContent } from 'pub-bbx-utils'

import { getSortAfterNodes} from '@src/util/approve'
import { useTenantId, useRootUser } from '@hooks/useRootWindow.ts';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { TaskApproversLabelEnum } from '@model/enum/LabelEnum'
import { approveApply } from '@src/api/ProjectManage.ts'

export default {
  name: 'propose-approve-dialog',
  props: {
    options: {
      type: Object,
      default: () => {}
    },
    approveId: {
      type: String,
      default: '',
    },
    // 模块的类型 
    moduleType: {
      type: String,
      default: '',
    },
    remarkRequired: {
      type: Boolean,
      default: false
    },
    taskId: {
      type: String,
      default: '',
    },
    top: {
      type: Boolean,
      default: false
    },
    unique: {
      type: Boolean,
      default: true
    },
    taskNo:{
      type: String,
      default: '',
    },
    // 自定义节点的id
    customNodeId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      isOpenData,
      visible: false,
      pending: false,
      chooseApprover: false,
      apprForm: {},
      approver: {},
      approversName: '',
      approversStaffIds: [],
      approveLevel: 1, // 审批等级
      multiApproverSetting: [], // 多级审批（2级以上审批）
      successBc: null,
      isSuccess: false,
      atUsers:[],
      fromVip: false,
      vipList: [],
      actionStr: '',// 操作的中文类型
      vipParams: {}, // 高级审批的返回参数
    }
  },
  computed: {
    remarkPlaceholder() {
      return this.remarkRequired ? this.$t('task.tip.proposeApproveTip2') : this.$t('task.tip.proposeApproveTip3')
    },
    cnNumName() {
      return [this.$t('common.base.number0'), this.$t('common.base.number1'), this.$t('common.base.number2'), this.$t('common.base.number3'), this.$t('common.base.number4'), this.$t('common.base.number5'), this.$t('common.base.number6'), this.$t('common.base.number7'), this.$t('common.base.number8'), this.$t('common.base.number9')];
    }
  },
  filters: {
    vipApproveNames(approvers) {
      return approvers.map(item => item.name).join(',')
    },
  },
  methods: {
    setNameLanguage(data) {
      if (!data.attribute.nameLanguage) return data.name
      let laEnv = this.$i18n.locale ;
      return data.attribute.nameLanguage[laEnv]
    },
    // 获取审批人多语言label
    getApproversLabel(name) {
      return TaskApproversLabelEnum[name] || name
    },
    /**
     * 更新多级选择的审批人
     */
    updateApprover(data, idx) {
      console.log(data, idx);
      this.$set(this.multiApproverSetting, idx, {
        ...this.multiApproverSetting[idx],
        approver: data
      })
    },
    async openDialog(data, successBc) {
      if (data.needVipApprove || (data.needApprove && this.moduleType === 'project')) {

        if (this.moduleType === 'project') {
          this.vipParams = data
        } else {
          this.vipParams = data.params
        }
        this.fromVip = true
        this.actionStr = data.action
        let vipJson = JSON.parse(data.attribute)
        if (vipJson?.cells) {
          // 开始解析数据
          let filterArr = await getSortAfterNodes(vipJson.cells)
          let approveArr = filterArr.filter((item => item.shape === 'approve-node'))
          this.vipList = approveArr
        }
      } else {
        if(Object.prototype.toString.call(successBc) === '[object Function]'){
          this.successBc = successBc;
        }
        // 重置
        this.approver = {};
        this.apprForm = { source: 'task' };
        this.apprForm.applyRemark = '';
        this.apprForm.params = data;
        this.chooseApprover = false;
        this.atUsers = []

        if (successBc && Object.keys(successBc).length) this.apprForm.params = {...this.apprForm.params, ...successBc}
        if (data.isOpt == 1) {
          this.chooseApprover = true;
        } else {
          this.approversName = data.approversName;
          const approversIds = data.approversStaffIds || data.approversStaffId;
          if(approversIds) {
            this.approversStaffIds = approversIds.split(',') || [];
          }
        }

        this.approveLevel = data.level || 1;
        this.multiApproverSetting = data.multiApproverSetting ? [...data.multiApproverSetting] : [];
      }

      this.visible = true;
    },

    submit() {
      if (this.fromVip) {
        if (this.moduleType === 'project') {
          // 项目管理的审批
          let approveVipParams = {
            bizId: this.taskId,
            remark: this.apprForm.applyRemark,
            module: 'project',
            params: {
              ...this.vipParams
            }
          }
          this.pending = true;
          approveApply(approveVipParams).then((res) => {
            if (res.success) { 
              this.$platform.alert(this.$platform.inDingTalk ? this.$t('task.tip.proposeApproveTip5') : this.$t('task.tip.proposeApproveTip6'));
              // 为提供jsp成功回调
              this.visible = false
              this.isSuccess = true
              if(this.successBc) return this.successBc();
              this.$emit('success')
              this.pending = false;
              // 刷新当前页面
              window.location.reload();
            } else {
              this.$platform.alert(res.message);
              if (res.errorCode == 1003) {
                window.location.reload();
              }
              this.pending = false;
            }
          })

        } else {
          // 审批说明必填校验
          if (!this.apprForm.applyRemark && this.remarkRequired) return this.$platform.notification({ type: 'error', title: this.$t('task.tip.proposeApproveTip4')})
          // 工单模块的审批
          let approveVipParams = {
            objId: this.taskId,
            action: this.actionStr,
            applyRemark: enCodeAtText(this.apprForm.applyRemark, this.atUsers),
            params: {
              ...this.vipParams
            }
          }
          if(this.customNodeId) {
            approveVipParams.nodeTaskBizId = this.customNodeId
          }
          
          let apprForm = _.cloneDeep(this.apprForm)
          let receivers = ''
          let query = ''
          if(this.apprForm.applyRemark){
            apprForm.applyRemark = enCodeAtText(this.apprForm.applyRemark, this.atUsers);
            receivers = getReceivers(this.apprForm.applyRemark, this.atUsers)
            const queryData = {
              receivers,
              tenantId: useTenantId().value,
              content: cutAtTextContent(this.apprForm.applyRemark),
              sendUserName: useRootUser().value?.displayName,
              bizId: this.taskId,
              bizNo: this.taskNo || this.$t('task.taskDetail'),
              md: this.$t('common.base.task')
            };
            query = '?';
            for (let i in queryData) {
              query += `&${i}=${queryData[i]}`;
            }
          }
          this.pending = true;
          TaskApi.createVipApprove(approveVipParams, query)
          .then((res) => {
            if (res.success && res.result) { 
              this.$platform.alert(this.$platform.inDingTalk ? this.$t('task.tip.proposeApproveTip5') : this.$t('task.tip.proposeApproveTip6'));
              // 为提供jsp成功回调
              this.visible = false
              this.isSuccess = true
              if(this.successBc) return this.successBc();
              this.$emit('success')
              // window.location.href = `/task/view/${this.taskId}`;
              this.pending = false;
              let fromId = window.frameElement.getAttribute('id');

              openAccurateTab({
                type: PageRoutesTypeEnum.PageTaskView,
                key: this.taskId,
                fromId,
              });
            } else {
              this.$platform.alert(res.message);
              if (res.errorCode == 1003) {
                window.location.reload();
              }
              this.pending = false;
            }
          }).catch(err => {
            this.pending = false;
          })
        }
      } else {

      // 审批人由发起人选择时
      const approveTip = this.approveLevel > 1 ? this.$t('task.tip.approveTip7', {data: this.$t('common.base.number1')}) : this.$t('task.tip.approveTip6')
      if (this.chooseApprover && !this.approver.userId) return this.$platform.alert(approveTip);

      for (let i = 0; i < this.multiApproverSetting.length; i++) {
        const approve = this.multiApproverSetting[i];
        if(approve.isOpt === 1){
          if(!approve.approver) return this.$platform.alert(this.$t('task.tip.approveTip7', {data: this.cnNumName[i + 2]}));
          if(!approve.approver.userId) return this.$platform.alert(this.$t('task.tip.approveTip7', {data: this.cnNumName[i + 2]}));
        }
      }

      // 审批说明必填校验
      if (!this.apprForm.applyRemark && this.remarkRequired) return this.$platform.notification({ type: 'error', title: this.$t('task.tip.proposeApproveTip4')})

      if (this.chooseApprover) this.apprForm.params.approveId = this.approver.userId;

      // 多级审批参数
      for (let i = 0; i < this.multiApproverSetting.length; i++) {
        const approve = this.multiApproverSetting[i];
        if(this.approveLevel > 1) {
          if (approve.isOpt === 1) this.apprForm.params.multiApproverSetting[i].approveId = approve.approver.userId;
        }
      }
      this.pending = true;

      let apprForm = _.cloneDeep(this.apprForm)
      let receivers = ''
      let query = ''
      if(this.apprForm.applyRemark){
        apprForm.applyRemark = enCodeAtText(this.apprForm.applyRemark, this.atUsers);
        receivers = getReceivers(this.apprForm.applyRemark, this.atUsers)
        let queryData = {
          receivers,
          tenantId: useTenantId().value,
          content: cutAtTextContent(this.apprForm.applyRemark),
          sendUserName: useRootUser().value?.displayName,
          bizId: this.taskId,
          bizNo: this.taskNo || this.$t('task.taskDetail'),
          md: this.$t('common.base.task')
        };
        query = '?';
        for (let i in queryData) {
          query += `&${i}=${queryData[i]}`;
        }
      }
      
      TaskApi.applyApprove(apprForm, query).then(async res => {
        if (res.status == 0) {
          this.$platform.alert(this.$platform.inDingTalk ? this.$t('task.tip.proposeApproveTip5') : this.$t('task.tip.proposeApproveTip6'));
          // 为提供jsp成功回调
          this.visible = false
          this.isSuccess = true
          if(this.successBc) return this.successBc();
          this.$emit('success')
          // window.location.href = `/task/view/${this.taskId}`;
          this.pending = false;
          let fromId = window.frameElement.getAttribute('id');

          openAccurateTab({
            type: PageRoutesTypeEnum.PageTaskView,
            key: this.taskId,
            fromId,
          });
        } else {
          if (res.errorCode == 1003) {
            window.location.reload();
          }
          let confirm = await this.$platform.confirm(res.message);
          if (confirm) {
            window.location.reload();
          }
          this.pending = false;
        }
      }).catch(err => {
        this.pending = false;
      })
      }
    },
    head(src){
      if(!src) return defaultAvatar;
      return src;
    },
    inputContent(event){
      let value = event.target.value;
      this.apprForm.applyRemark = value;
    },
    close() {
      this.visible = false
      this.$emit('close', {
        isSuccess: this.isSuccess
      })
    },

  },
  components: {
    [FormUser.name]: FormUser
  }
}
</script>

<style lang="scss">
.vip-info {
  margin: 20px 0 10px 0;
}
.task-need-approve-dialog {
  .form-item {
    margin-bottom: 10px;
    align-items: baseline;
  }
  // 以下为jsp页面兼容样式
  .form-item-required {
    color: red;
  }
  .base-modal {
    .base-modal-body {
      padding: 20px;

      .base-modal-content {
        textarea {
          width: 100%;
        }

        p {
          margin-bottom: 8px;

          &.tips {
            color: #999;
            font-size: 12px;
          }

          &.base-upload-placeholder {
            margin-bottom: 0;
          }
        }

        button{
          height: 24px;
          line-height: 32px;
          width: 24px;

          padding: 0;
          margin: 0;
          outline: none;
          color: #666;
          border: none;
          background-color: transparent;
          transition: color ease .15s;

          i {
            font-size: 14px;
          }

          &:hover{
            color: #e84040;
          }
        }
      }

      .el-button {
        min-width: auto;
        max-width: auto;
      }
    }

    .base-modal-footer {
      text-align: right;
    }

    .task-back-dialog {
      p {
        font-size: 12px;
      }
    }
  }
}

</style>

<style lang="scss" scoped>
.approve-steps{
  margin-top: 20px;
}

// elemeny-ui
::v-deep .el-step__description{
  padding: 0;
}

::v-deep .el-steps, .el-step{
  width: auto !important;
}

::v-deep .el-step__head.is-process{
  color: #BFBFBF;
  border-color: #BFBFBF;
}

textarea {
  width: 100%;
}
</style>
